package com.qingke.oms.command.shop;

import java.util.ArrayList;
import java.util.List;

import com.qingke.oms.dao.OrderManagementSystemDAO;
import com.qingke.oms.pojo.GoodsRecord;
import com.qingke.oms.util.OMSConsole;

public interface UpdateGoodsStatistic {
	default void updateGoodsStatistic(){
		OrderManagementSystemDAO dao=new OrderManagementSystemDAO();
		List<GoodsRecord> onGoodsRecord=dao.selectCountShelfRecordByShelfStatus("on shelf");
		List<GoodsRecord> offGoodsRecord=dao.selectCountShelfRecordByShelfStatus("off shelf");
		List<GoodsRecord> shipmentGoodsRecord=dao.selectCountShipmentRecordByShelfStatus("not shipped");
		
		List<GoodsRecord> newest=new ArrayList<>();
		for(GoodsRecord on:onGoodsRecord){
			for(GoodsRecord off:offGoodsRecord){
				if(on.getShopId()==off.getShopId()&&on.getGoods().getId()==off.getGoods().getId()){
					on.setQuantity(on.getQuantity()-off.getQuantity());
				}
			}
			for(GoodsRecord shipment:shipmentGoodsRecord){
				if(on.getShopId()==shipment.getShopId()&&on.getGoods().getId()==shipment.getGoods().getId()){
					on.setQuantity(on.getQuantity()-shipment.getQuantity());
				}
			}
			GoodsRecord gr=new GoodsRecord();
			gr.setShopId(on.getShopId());
			gr.setGoods(on.getGoods());
			gr.setQuantity(on.getQuantity());
			newest.add(gr);
		}

		for(GoodsRecord gr:newest){

			boolean isExist=dao.isGoodsStatisticExistByShopIdAndGoodsId(gr.getShopId(),gr.getGoods().getId());
			if(isExist){
				GoodsRecord goodsRecord=dao.selectGoodsStatisticByShopIdAndGoodsId(gr.getShopId(),gr.getGoods().getId());
				int stock=goodsRecord.getQuantity();
				if(stock!=gr.getQuantity()){
					boolean isSuccess=dao.updateGoodsStatisticStockByShopIdAndGoodsId(gr.getQuantity(),gr.getShopId(),gr.getGoods().getId());
					if(!isSuccess){
						OMSConsole.println("update failed.");
						break;
					}
				}
			}
			else{
				boolean isSuccess=dao.insertGoodsStatistic(gr.getShopId(),gr.getGoods().getId(),gr.getQuantity());
				if(!isSuccess){
					OMSConsole.println("update failed.");
					break;
				}
			}
		}
		
	}
}
